/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>Project: 209715200 (200MB)  10485760(10MB)
 * <p>Powered by webrx On 2022-03-11 11:32:25
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
@WebServlet("/uploads") @MultipartConfig
public class Uploads extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String name = req.getParameter("user");
        //获取所有的表单元素（file text ）
        Collection<Part> ps = req.getParts();

        StringBuilder sbu = new StringBuilder();
        sbu.append(String.format("<h1>上传人：%s</h1>", name));
        for (Part p : ps) {
            if(p.getContentType()==null || p.getSize()==0) continue;
            String filename = p.getSubmittedFileName();
            boolean f = true;
            String n = "";
            //控制上传的格式(jpg,gif,png,rar,zip,pdf)
            Set<String> allow = new HashSet<>(List.of("jpg"));
            String ext = filename.substring(filename.lastIndexOf(".")+1);
            if(!allow.contains(ext)){
                f = false;
                n = String.format("上传失败，不允许上的此(%s)",ext);
            }
            //控制上传的文件的大小 10485760 10MB
            long maxsize =  10485760;
            if(f) {
                if (p.getSize() >= maxsize) {
                    f = false;
                    n = String.format("上传失败，不允许上超出10MB的文件（%d）", p.getSize());
                }
            }
            //控制命名及位置
            filename = UUID.randomUUID().toString().toLowerCase().concat(".").concat(ext);
            //filename = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssS")).concat(".").concat(ext);

            //user.jpg  user.jpg  user(1).jpg  user(2).jpg

            //上的位置 /upload/user/202203 xxx
            //C:\\javaweb\\uploads\\target\\uploads-1.0\\upload\\user\\202203
            String path = req.getServletContext().getRealPath(String.format("/upload/user/%tY%<tm",System.currentTimeMillis()));
            File ff = new File(path);
            if(!ff.exists()) ff.mkdirs();

            if(f) {
                p.write(String.format("%s/%s",path,filename));
                sbu.append(String.format("<h3>文件名：%s</h3>", p.getSubmittedFileName()));
                sbu.append(String.format("<h3>类型：%s</h3>", p.getContentType()));
                sbu.append(String.format("<h3>大小：%d字节</h3>", p.getSize()));
                sbu.append(String.format("<hr>"));
            }
        }

        /*
        ps.stream().filter(e->resp.getContentType()!=null && e.getSize()>0).forEach(p->{
           sbu.append(String.format("<h3>文件名：%s</h3>",p.getSubmittedFileName()));
           sbu.append(String.format("<h3>类型：%s</h3>",p.getContentType()));
           sbu.append(String.format("<h3>大小：%d字节</h3>",p.getSize()));
           sbu.append(String.format("<hr>"));

        });
         */

        print(resp,sbu.toString());


    }
    protected void print(HttpServletResponse resp,String msg) throws IOException {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<meta charset=\"utf-8\">");
        out.println("<title>玉灵 QQ:7031633 Email:webrx@126.com</title>");
        out.println("<meta name=\"keywords\" content=\"关键字\">");
        out.println("<meta name=\"description\" content=\"简介\">");
        out.println("</head>");
        out.println("<body>");

        out.printf("<h3>%s</h3>",msg);

        out.println("</body>");
        out.println("</html>");
        out.flush();
        out.close();
    }
}
